package sw6.programExample;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import sw6.lib.internal.PrivateDefinitions;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;

public final class InsertSettings {
	private InsertSettings() { }
	
	/* ***************************************************** */
	/*                     INSERTERS                         */
	/* ***************************************************** */
    public static void insertBoolean(Context context, String appName, String varName, boolean varValue) {
    	ContentValues contentValues = new ContentValues();
    	contentValues.put(PrivateDefinitions.VAR_VALUE, varValue);
    	insertSetting(context, appName, varName, PrivateDefinitions.BOOLEAN, contentValues);
    }
    
    public static void insertInteger(Context context, String appName, String varName, int varValue) {
    	ContentValues contentValues = new ContentValues();
    	contentValues.put(PrivateDefinitions.VAR_VALUE, varValue);
    	insertSetting(context, appName, varName, PrivateDefinitions.INTEGER, contentValues);
    }
    
    public static void insertString(Context context, String appName, String varName, String varValue) {
    	ContentValues contentValues = new ContentValues();
    	contentValues.put(PrivateDefinitions.VAR_VALUE, varValue);
    	insertSetting(context, appName, varName, PrivateDefinitions.STRING, contentValues);
    }
    
    private static void insertSetting(Context context, String appName, String varName, String dataType, ContentValues contentValues) {
    	Uri settingRequest = Uri.withAppendedPath(PrivateDefinitions.CONTENT_URI, dataType + "/" + appName + "/" +  varName);
		context.getContentResolver().insert(settingRequest, contentValues);
    }
    
	public static void insertObject(Context context, String appName, String varName, Object varValue) {
    	ContentValues contentValues = new ContentValues();
    	
		ByteArrayOutputStream baos 	= new ByteArrayOutputStream();
	    ObjectOutputStream oos 		= null;
		
	    try {
			oos = new ObjectOutputStream(baos);
			oos.writeObject(varValue);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		byte[] byteArrayOutputSerialized = baos.toByteArray();
    	
    	contentValues.put(PrivateDefinitions.VAR_VALUE, byteArrayOutputSerialized);
    	Uri settingRequest = Uri.withAppendedPath(PrivateDefinitions.CONTENT_URI, PrivateDefinitions.OBJECT + "/" + appName + "/" +  varName + "/" + varValue.getClass().getCanonicalName());
		context.getContentResolver().insert(settingRequest, contentValues);
    }
}
